import { APIItem } from '../types';
import { getRootAPI } from '../store';

export interface controllerResult {
  name: string;
  apiMap: Map<string, number>;
  apiNumber: number;
}

export interface controllersResult {
  controllersNumber: number;
  controllers: controllerResult[];
}

export function parseControllers() {
  const controllers = getRootAPI();

  const controllersNumber = controllers.length;

  const list = controllers.map((controller) => {
    const { apiNumber, apiMap } = getApiCount(controller.items);
    return {
      name: controller.name,
      apiMap,
      apiNumber,
    };
  });

  return {
    controllersNumber,
    controllers: list,
  };
}

export function getApiCount(items: APIItem[]) {
  const apiNumber = items.length;
  const apiMap = new Map();

  items.forEach((item) => {
    switch (item.api.method) {
      case 'get':
        const getcount = apiMap.get('get');
        if (!getcount) {
          apiMap.set('get', 1);
        } else {
          apiMap.set('get', getcount + 1);
        }
        break;

      case 'post':
        const postcount = apiMap.get('post');
        if (!postcount) {
          apiMap.set('post', 1);
        } else {
          apiMap.set('post', postcount + 1);
        }
        break;

      case 'put':
        const putcount = apiMap.get('put');
        if (!putcount) {
          apiMap.set('put', 1);
        } else {
          apiMap.set('put', putcount + 1);
        }
        break;

      case 'delete':
        const deletecount = apiMap.get('delete');
        if (!deletecount) {
          apiMap.set('delete', 1);
        } else {
          apiMap.set('delete', deletecount + 1);
        }
        break;

      default:
        break;
    }

    item.api.method;

    return {};
  });

  return {
    apiNumber,
    apiMap,
  };
}
